package com.huali.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;

@WebServlet(name = "LoginServlet", value = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端传递的参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //进行账号密码的校验
        if ("123".equals(username)) {
            if ("123".equals(password)) {
                //创建cookie对象
                Cookie cookie = new Cookie(username, password);
                //将cookie添加到浏览器
                response.addCookie(cookie);

                //将登录信息存放在session中
                HttpSession session = request.getSession();
                //创建map 存放登陆信息
                HashMap<String, String> map = new HashMap<>();
                map.put(username, password);
                //将map对象存放在session中
                session.setAttribute("user", map);

                //进行页面跳转 转发
                request.getRequestDispatcher("/admin.html").forward(request, response);
            }
        }
        //重定向
        response.sendRedirect("/error.html");
    }
}
